/*
 *
 自定义tab页外层框架
 *
 *reClass:自定义外层覆盖样式
 * callParent:点击按钮后通知父控件当前active
 *itemWidth：列宽，可为空
 * reTabTitle：标题
 * */
'use strict';
var React = require('react');
class ReTab extends React.Component {
    constructor(props) {
        super(props);
        //此处服务端前端都会执行，未避免二次动画，故先设置成999
        this.state = {
            active: 9999,
            mouseLeftPosition: 0,
            flag: false
        };
        this.renderTabTitles = this.renderTabTitles.bind(this);
        this.renderTabContent = this.renderTabContent.bind(this);
        this.showTabOrNot = this.showTabOrNot.bind(this);
        this.setActiveTab = this.setActiveTab.bind(this);
        this.getMainClass = this.getMainClass.bind(this);
        this.ReTabMouseDown = this.ReTabMouseDown.bind(this);
        this.ReTabMouseUp = this.ReTabMouseUp.bind(this);
        this.ReTabMouseMove = this.ReTabMouseMove.bind(this);
        this.ReTabMouseOut=this.ReTabMouseOut.bind(this);
    }

    //此处只有客户端才会执行，控件加载完成后再初始化active值，防止后端渲染后前端再次渲染造成两次动画
    componentDidMount() {
        var activeItem = this.props.activeItem ? this.props.activeItem : 0;
        this.setState({
            active: activeItem
        });

        if (activeItem > 0) {
            this.refs.ReTab_Down.style.left = activeItem * 100 / this.props.children.length + '%';
        }
    }


    getElementTop(element) {
        var actualTop = element.offsetTop;
        var current = element.offsetParent;
        while (current !== null) {
            actualTop += current.offsetTop;
            current = current.offsetParent;
        }
        return actualTop;
    }

    getElementLeft(element) {
        var actualLeft = element.offsetLeft;
        var current = element.offsetParent;
        while (current !== null) {
            actualLeft += current.offsetLeft;
            current = current.offsetParent;
        }
        return actualLeft;
    }

    //点击激活对应tab,添加水波纹效果
    setActiveTab(activeId, event) {
        this.refs["ripple" + activeId].className = "ripple";
        var currentTarget = this.refs["ReTab_Title_Item" + activeId];
        var posX = this.getElementLeft(currentTarget),
            posY = this.getElementTop(currentTarget),
            buttonWidth = currentTarget.offsetWidth,
            buttonHeight = currentTarget.offsetHeight;

        if (buttonWidth >= buttonHeight) {
            buttonHeight = buttonWidth;
        } else {
            buttonWidth = buttonHeight;
        }
        var x = event.pageX - posX - buttonWidth / 2;
        var y = event.pageY - posY - buttonHeight / 2;

        this.refs["ripple" + activeId].style.width = buttonWidth + "px";
        this.refs["ripple" + activeId].style.height = buttonHeight + "px";
        this.refs["ripple" + activeId].style.top = y + 'px';
        this.refs["ripple" + activeId].style.left = x + 'px';
        this.refs["ripple" + activeId].className += " rippleEffect";
        var childrenCount = this.props.children.length;
        this.refs.ReTab_Down.style.left = activeId * 100 / childrenCount + '%';
        this.setState({
            active: activeId
        });
        if (this.props.callParent) {
            this.props.callParent(activeId);
        }
        //根据参数确定是否需要改变url，添加#号用于定位tabItem
        if(this.props.changeUrl){
            if(location.href.indexOf('#')>0){
                location.href=location.href.split('#')[0]+ '#active' +activeId;
            }
            else {
                location.href = location.href + '#active' + activeId;
            }
        }
    }

    //渲染tab标题
    renderTabTitles() {
        var itemStyle;
        if (this.props.itemWidth != undefined) {
            itemStyle = {
                width: this.props.itemWidth
            };
        }
        else {
            var childrenCount = this.props.children.length;
            var singleItemWidth = 100 / childrenCount;
            itemStyle = {
                width: singleItemWidth + "%"
            };
        }
        return this.props.children.map((item, i) => {
            return <div key={"ReTab_Title_Item"+i} ref={"ReTab_Title_Item"+i} className="ReTab_Title_Item"
                        style={itemStyle} onClick={this.setActiveTab.bind(this,i)}>
                {item.props.reTabTitle}
                <span className="ripple" ref={"ripple"+i} id={"ripple"+i}></span>
            </div>

        });
    }

    //根据状态判断当前页面是否显示
    showTabOrNot(i) {
        if (i == this.state.active) {
            return "ReTab_Title_Contents_Item active";
        }
        else {
            return 'ReTab_Title_Contents_Item';
        }
    }

    //渲染tab内容
    renderTabContent() {
        return this.props.children.map((item, i) => {
            return <div key={"ReTab_Title_Contents_Item"+i} className={this.showTabOrNot(i)}>
                {item}
            </div>
        });
    }

    //获取替换的主样式
    getMainClass() {
        if (this.props.reClass != undefined) {
            return "ReTab_Container " + this.props.reClass;
        }
        else {
            return 'ReTab_Container';
        }
    }


    //按下鼠标拖动前获取当前鼠标的位置并记录状态
    ReTabMouseDown(event) {
        var e = event ? event : window.event;
        this.setState({
            flag: true,
            mouseLeftPosition: e.clientX
        });
    }


    //放开鼠标时记录当前为松开鼠标的状态
    ReTabMouseUp(event) {
        this.setState({
            flag: false
        })
    }

    //离开tab时改变状态，防止按下鼠标的同时离开了tab导致状态混乱
    ReTabMouseOut(e) {
        var location=e.toElement||e.relatedTarget;
        var s = this.refs.ReTab_Adapter;
        if (document.all) {
            if (!s.contains(location)) {
                this.setState({
                    flag: false
                })
            }
        } else {
            //最终目的dom在控件内部时不触发
            var reg = location.compareDocumentPosition(s);
            if ((reg != 10 )) {
                this.setState({
                    flag: false
                })
            }
        }
    }

    //拖动逻辑
    ReTabMouseMove(event) {
        if(this.state.flag) {
            var titleWidth = this.refs.ReTab_Title.offsetWidth;
            var adapterWidth = this.refs.ReTab_Adapter.offsetWidth;
            var titleLeft = parseFloat(this.refs.ReTab_Title.style.left.replace('px', ''));
            var howFarYouMove=event.clientX - this.state.mouseLeftPosition;
            if (titleWidth > adapterWidth && (howFarYouMove + titleLeft + titleWidth >= adapterWidth && titleLeft <= 0)) {
                this.refs.ReTab_Title.style.left = (howFarYouMove + titleLeft > 0 ? 0 : howFarYouMove + titleLeft) + 'px';
            }
        }
    }

    //tab标题比父节点长的时候显示按钮以滚动标题
    /*    getSliderItemClass() {
     if (this.props.itemWidth != undefined && this.refs.ReTab_Title.offsetWidth > this.refs.ReTab_Adapter.offsetWidth) {
     return 'showSliderItems'
     }
     else {
     return 'hide'
     }
     }*/

    render() {
        var downStyle;
        var titleStyle;
        //检测是否有定义单个标签宽度，有的话做特殊样式处理
        if (this.props.itemWidth != undefined) {
            downStyle = {
                width: this.props.itemWidth
            };
            titleStyle = {
                width: 'auto',
                left: 0
            }
        }
        else {
            var childrenCount = this.props.children.length;
            var singleItemWidth = 100 / childrenCount;
            downStyle = {
                width: singleItemWidth + "%"
            };
        }
        return (
            <div className={this.getMainClass()}>
                <div className="ReTab_TitleBackground">
                    <div className="ReTab_Adapter" ref="ReTab_Adapter" onMouseOut={this.ReTabMouseOut}>
                        <div className="ReTab_Title" ref="ReTab_Title" style={titleStyle}
                             onMouseDown={this.ReTabMouseDown} onMouseUp={this.ReTabMouseUp}
                             onMouseMove={this.ReTabMouseMove} >
                            {this.renderTabTitles()}
                            <div className="ReTab_Down" style={downStyle} ref="ReTab_Down"></div>
                        </div>
                    </div>
                </div>
                <div className="ReTab_Contents">
                    {this.renderTabContent()}
                </div>
            </div>
        );
    }
}

ReTab.propTypes = {
    reClass: React.PropTypes.string,
    callParent: React.PropTypes.func,
    itemWidth: React.PropTypes.string
};

module.exports = ReTab;
